package com.zhang;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
	
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	public static Connection getConnection() {
		if(tl.get() == null) {
			Connection con = null;
			try {
				Class.forName("com.mysql.jdbc.Driver");
				con =  DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8", "root", "root");
			} catch (Exception e) {
				e.printStackTrace();
			}
			tl.set(con);
		}
		return tl.get();
	}

	public static void closeConnection() {
		if(tl.get() != null) {
			Connection con = tl.get();
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			tl.set(null);
		}
	}

	public static void main(String[] args)  throws Exception {
		System.out.println(DBUtil.getConnection());
	}
}
